<template>
  <div class="role-container">
    <div class="left-wrapper">
      <div
        v-for="(item, index) in roleList"
        :key="item.roleId"
        class="role-item"
        :class="{ active: index === activeIndex }"
        @click="highLight(index)"
      >
        <div class="role-info">
          <!-- svg-icon是组件 -->
          <!-- user-active是高亮图标，通过替换图标来实现高亮效果 -->
          <svg-icon
            :icon-class="index === activeIndex ? 'user-active' : 'user'"
            class="icon"
          />
          {{ item.roleName }}
        </div>
        <!-- 更多 -->
        <div class="more">
          <el-dropdown>
            <span class="el-dropdown-link">
              <svg-icon icon-class="more" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="edit(item.roleId)">
                编辑角色
              </el-dropdown-item>
              <el-dropdown-item @click.native="del(item.roleId)">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <el-button
        class="addBtn"
        size="mini"
        @click="$router.push('/sys/addRole')"
      >
        添加角色
      </el-button>
    </div>
    <div class="right-wrapper">
      <!-- tab栏 -->
      <!-- v-model会获取el-tab-pane的name的值 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="功能权限" name="right">
          <!-- 权限列表 -->
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <!-- prop：配置不一致的键名 -->
              <!-- show-checkbox：复选框 -->
              <!-- default-expand-all：是否默认展开所有节点 -->
              <!-- node-key="id"：用于设置选中节点，值是data（即item.children）每一项的唯一标识 -->
              <el-tree
                ref="tree"
                :data="item.children"
                :props="defaultProps"
                show-checkbox
                :default-expand-all="true"
                node-key="id"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`成员（${total}）`" name="employee">
          <div class="user-wrapper">
            <el-table :data="userList" style="width: 100%">
              <el-table-column type="index" width="250" label="序号" />
              <el-table-column prop="name" label="员工姓名" />
              <el-table-column prop="userName" label="登录账号" />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import {
  getSysRoleAPI,
  getTreeListAPI,
  rightDetailAPI,
  roleUserListAPI,
  delRoleAPI
} from '@/api/system'
export default {
  name: 'Role',
  data () {
    return {
      roleList: [],
      activeIndex: 0, // 默认高亮第一个标签
      treeList: [],
      defaultProps: {
        label: 'title'
        // 禁用复选框方案2
        // disabled: function () {
        //   return true
        // },//disabled的值是一个函数
        // 方案2的简写版本
        // disabled: () => true
      }, // el-tree组件只认识children和label键名，键名不一致的需要修改
      activeName: 'right', // 默认显示权限列表
      params: {
        page: 1,
        pageSize: 10
      },
      total: 0,
      userList: []
    }
  },
  async created () {
    await this.getSysRole()
    await this.getTreeList()
    this.highLight(0) // 页面一加载就得有数据选中
  },
  methods: {
    // 查询所有角色
    async getSysRole () {
      const res = await getSysRoleAPI()
      // console.log('查询所有角色', res)
      this.roleList = res.data
    },
    // 标签切换（包含高亮显示）
    highLight (index) {
      this.activeIndex = index
      const roleId = this.roleList[index].roleId
      this.rightDetail(roleId) // 功能权限tab栏切换页面
      this.roleUserList(roleId) // 成员tab栏切换页面，这个函数也可以在tab切换的时机调用
    },
    // 查询所有功能权限(树形)
    async getTreeList () {
      const res = await getTreeListAPI()
      // console.log('所有功能权限(树形)', res)
      this.treeList = res.data
      this.addDisabled(this.treeList)
    },
    // 禁用复选框方案1
    addDisabled (treeList) {
      // console.log(this.treeList)
      treeList.forEach(ele => {
        ele.disabled = true
        if (ele.children) {
          this.addDisabled(ele.children)
        }
      })
    },
    // 查询当前角色详情-权限和分配人数
    async rightDetail (roleId) {
      const res = await rightDetailAPI(roleId)
      // console.log('哪些权限打钩', res)
      // console.log(res.data.perms)//由权限id组成的二维数组

      // 设置选中节点有2种方式，node和key，这里用key方式（setCheckedKeys）
      // console.log(this.$refs.tree) // 因为el-tree是被v-for遍历出来的，所以得到一个数组结果，数组里有5项
      const trees = this.$refs.tree
      trees.forEach((ele, index) => {
        ele.setCheckedKeys(res.data.perms[index]) // res.data.perms的每一项是个由权限id组成的一维数组
      })
    },
    // 角色关联的用户列表
    async roleUserList (roleId) {
      const res = await roleUserListAPI({
        ...this.params,
        roleId
      })
      // console.log('成员列表', res)
      this.total = res.data.total
      this.userList = res.data.rows
    },
    // 编辑角色
    edit (roleId) {
      this.$router.push(`/sys/addRole?roleId=${roleId}`)
    },
    // 删除角色
    del (roleId) {
      this.$confirm('确定删除吗？', '温馨提示')
        .then(async () => {
          const res = await delRoleAPI(roleId)
          console.log('删除角色', res)
          this.$message.success('删除成功')
          this.getSysRole()
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped lang="scss">
.role-container {
  display: flex;
  font-size: 14px;
  background-color: #fff;
  padding: 20px;
  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
      }
    }

    .more {
      display: flex;
      align-items: center;
    }
    .addBtn {
      width: 100%;
      margin-top: 20px;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;
        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }

    ::v-deep .el-tabs__nav-wrap {
      padding-left: 20px;
    }

    .user-wrapper {
      padding: 20px;
    }
  }
}
</style>
